package com.duke.shaking.widget;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import com.duke.shaking.R;
import com.duke.shaking.pojo.CacheImage;
import com.duke.shaking.pojo.User;
import com.duke.shaking.pojo.UserPhoto;
import com.duke.shaking.utils.AppUtils;
import com.duke.shaking.utils.LocationUtils;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.GridView;

public class PhotoGridView extends GridView {
	private final int boysPhotosInAssets = 30;
	private final int girlsPhotosInAssets = 39;
	
	private PhotoGridAdapter adapter;
	private List<UserPhoto> photos;
	private int numPhotos = 12;
	private int numCols = 4;
	private int numRows = 3;
	private int sex = User.sex_unk;
	
	public PhotoGridView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(attrs);
		if (!this.isInEditMode()) {
			photos = loadPhotos(numPhotos);
			adapter = new PhotoGridAdapter(context, photos);
			setAdapter(adapter);
		}
		setFadingEdgeLength(0);
	}
	
	private void init(AttributeSet attrs) {
		initAttrs(attrs);
		numPhotos = numCols * numRows;
	}
	
	protected void initAttrs(AttributeSet attrs) {
		TypedArray a = getContext().obtainStyledAttributes(attrs,
                R.styleable.shaking);
		if (a == null) {
			return;
		}
		
		for (int i = 0; i < a.getIndexCount(); i ++) {
            int attr = a.getIndex(i);
            switch (attr) {
            case R.styleable.shaking_numCols:
            	numCols = a.getInt(attr, numCols);
            	break;
            case R.styleable.shaking_numRows:
            	numRows = a.getInt(attr, numRows);
            	break;
            case R.styleable.shaking_sex:
            	String str = a.getString(attr);
            	if (str != null) {
            		if (str.equalsIgnoreCase("male")) {
            			sex = User.sex_male;
            		}
            		else if (str.equalsIgnoreCase("female")) {
            			sex = User.sex_female;
            		}
            	}
            	
            }
        }
        a.recycle();
	}
	
	@Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int width = MeasureSpec.getSize(widthMeasureSpec);
		int photoWidth = width / numCols;
		int photoHeight = photoWidth;
		//int height = MeasureSpec.getSize(heightMeasureSpec);
		// width and height of photo set to the same value
		if (adapter != null) {
			adapter.setPhotoSize((int)photoWidth, (int)photoHeight);
		}
		//int height = numRows * photoHeight;
		//heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, 
		//		MeasureSpec.getMode(heightMeasureSpec));
		//this.setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
		int expandSpec = MeasureSpec.makeMeasureSpec(   
                Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
	}
	
	private String getCityName(Random r) {
		if (LocationUtils.cityName != null
			&& !LocationUtils.cityName.equals("")) {
			return LocationUtils.cityName;
		}
		String[] hotCities = getContext().getResources().getStringArray(R.array.hot_cities);
		if (hotCities != null && hotCities.length > 0) {
			int cn = r.nextInt(hotCities.length);
			if (cn >= hotCities.length) {
				cn = 0;
			}
			return hotCities[cn];
		}
		return "";
	}
	
	private UserPhoto genRandomPhoto(Random r) {
		int n = r.nextInt(3000);
		String sexTitle = null, locTitle = getCityName(r), path = AppUtils.getDummyPhotoDir();
		int split = 1000;
		if (sex == User.sex_female) {
			split = 0;
		}
		else if (sex == User.sex_male) {
			split = 3000;
		}
		
		if (n < split) {
			sexTitle = getResources().getString(R.string.male);
			n = r.nextInt(boysPhotosInAssets);
			if (n >= boysPhotosInAssets) {
				n = 0;
			}
			path = String.format("%s/boys/boy(%d).jpg", path, n); 
		}
		else {
			sexTitle = getResources().getString(R.string.female);
			n = r.nextInt(girlsPhotosInAssets);
			if (n >= girlsPhotosInAssets) {
				n = 0;
			}
			path = String.format("%s/girls/girl(%d).jpg", path, n); 
		}

		String title = locTitle + sexTitle;
		
		UserPhoto photo = new UserPhoto(path, CacheImage.LocationType_ASSETS);
		photo.setTitle(title);
		return photo;
	}
	
	private List<UserPhoto> loadPhotos(int num_photos) {
		List<UserPhoto> photos = new LinkedList<UserPhoto>();
		int i;
		Random r = new Random();
		r.setSeed((new Date()).getTime());

		for (i = 0; i < num_photos;) {
			UserPhoto p = genRandomPhoto(r);
			boolean exists = false;
			for (UserPhoto ep : photos) {
				if (ep.getUrl().equals(p.getUrl())) {
					exists = true;
					break;
				}
			}
			if (exists) {
				continue;
			}
			Log.i("shaking", "random photo path: " + p.getUrl());
			photos.add(p);
			i ++;
		}
		return photos;
	}

}
